package per.hx.bs.web.yw.controller;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import per.hx.bs.base.BaseController;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.domain.ExcelData;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.base.domain.Tree;
import per.hx.bs.entity.sys.SysFileDO;
import per.hx.bs.entity.sys.SysUserDO;
import per.hx.bs.entity.yw.YwAppraisalDataDO;
import per.hx.bs.entity.yw.YwAppraisalRecordDO;
import per.hx.bs.util.DateUtils;
import per.hx.bs.util.ExcelUtils;
import per.hx.bs.util.PageUtils;
import per.hx.bs.util.Query;
import per.hx.bs.vo.AppraisalUserVO;
import per.hx.bs.web.sys.service.SysFileService;
import per.hx.bs.web.sys.service.SysUserService;
import per.hx.bs.web.yw.service.YwAppraisalApplyService;
import per.hx.bs.web.yw.service.YwAppraisalService;
import per.hx.bs.web.yw.service.YwAppraisalUserService;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author HuXing
 * @date 2018/4/16  8:20
 */
@Controller
@RequestMapping(value = "yw/appraisalUser")
public class AppraisalUserController extends BaseController {
    private final String prefix = "yw/appraisalUser/";


    private final
    YwAppraisalUserService appraisalUserService;

    private final
    SysUserService userService;

    private final
    YwAppraisalApplyService applyService;

    private final
    SysFileService fileService;

    @Autowired
    public AppraisalUserController(YwAppraisalUserService appraisalUserService, SysUserService userService, YwAppraisalApplyService applyService, SysFileService fileService, YwAppraisalService appraisalService) {
        this.appraisalUserService = appraisalUserService;
        this.userService = userService;
        this.applyService = applyService;
        this.fileService = fileService;
    }

    @BsCLog("进入人员考核界面")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = {"/", ""})
    public String index() {
        return prefix + "appraisalUser";
    }

    @BsCLog("获取需要考核的人员 根据用户角色")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/userTree")
    @ResponseBody
    public Tree getAppraisalUser() {

        return JSON.parseObject(appraisalUserService.getUserTree(getUserId()), Tree.class);
    }


    @BsCLog("获取人员列表")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/user/list")
    @ResponseBody
    public PageUtils userList(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<AppraisalUserVO> sysUserList = appraisalUserService.userList(query);
        int total = appraisalUserService.userCount(query);
        return new PageUtils(sysUserList, total);
    }

    @BsCLog("进入人员考核管理界面")
    @RequiresPermissions("yw:kh:user:add")
    @GetMapping(value = "/userAdd")
    public String userAdd() {
        return prefix + "userAdd";
    }

    @BsCLog("获取改变考核人员状态")
    @RequiresPermissions("yw:kh:user:change")
    @GetMapping(value = "/user/change/{userId}")
    @ResponseBody
    public ReturnDTO userChange(@PathVariable("userId") Long userId) {
        return ReturnDTO.check(appraisalUserService.userChange(userId));
    }

    @BsCLog("进入人员考核管理界面")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/list/appraisalUser")
    @ResponseBody
    public List<AppraisalUserVO> appraisalUser() {
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("type", "isAdd");
        return appraisalUserService.userList(map);
    }

    @BsCLog("获取人员的信息考核")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<YwAppraisalRecordDO> recordDOS = appraisalUserService.list(query);
        int total = appraisalUserService.count(query);
        return new PageUtils(recordDOS, total);
    }

    @BsCLog("直接添加考核结果")
    @RequiresPermissions("yw:kh:add")
    @GetMapping(value = "/recordAdd")
    public String recordAdd(Long userId, Model model) {
        SysUserDO userDO = userService.get(userId);
        model.addAttribute("userDO", userDO);
        return prefix + "recordAdd";
    }

    @BsCLog("直接添加考核结果")
    @RequiresPermissions("yw:kh:add")
    @PostMapping(value = "/recordAdd")
    @ResponseBody
    public ReturnDTO recordAdd(YwAppraisalRecordDO recordDO) {
        recordDO.setCreateId(getUserId());
        if (recordDO.getRecordAmount() == null) {
            recordDO.setRecordAmount(1);
        }
        recordDO.setRecordMoney(recordDO.getItemMoney() * recordDO.getRecordAmount());
        return ReturnDTO.check(appraisalUserService.insertRecord(recordDO));
    }


    @BsCLog("导出excel")
    @RequiresPermissions("yw:kh:excel")
    @GetMapping(value = "/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestParam String userId, @RequestParam String searchDate) {

        SysUserDO userDO = userService.get(Long.parseLong(userId));
        ExcelData excelData = new ExcelData();
        excelData.setSubject("绩效考核详情");
        excelData.setMessage("考核用户：" + userDO.getName() + "导出人:" + getName() + "   导出时间:" + DateUtils.formatDateTime(new Date()));
        excelData.setName(userDO.getName() + "（" + searchDate + "）" + "绩效考核.xlsx");
        List<String> titles = new ArrayList<String>();
        titles.add("一级指标");
        titles.add("二级指标");
        titles.add("指标类型");
        titles.add("单项金额");
        titles.add("金额类型");
        titles.add("考核数量");
        titles.add("最终金额");
        titles.add("录入时间");
        excelData.setTitles(titles);

        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("userId", userId);
        map.put("searchDate", searchDate);
        List<YwAppraisalRecordDO> recordDOS = appraisalUserService.list(map);

        List<List<Object>> rows = new ArrayList<List<Object>>();

        if (recordDOS != null && !recordDOS.isEmpty()) {
            for (YwAppraisalRecordDO recordDO : recordDOS) {
                List<Object> row = new ArrayList<Object>();
                row.add(recordDO.getTypeName());
                row.add(recordDO.getItemName());
                row.add("0".equals(recordDO.getItemType()) ? "奖励" : "处罚");
                row.add(recordDO.getItemMoney());
                row.add(recordDO.getItemUnit());
                row.add(recordDO.getRecordAmount());
                row.add(recordDO.getRecordMoney());
                row.add(DateUtils.formatDateTime(recordDO.getCreateDate()));
                rows.add(row);
            }
        }
        excelData.setRows(rows);
       /* try {
            File file = new File("C:/Users/HuXing/Desktop/" + excelData.getName());
            FileOutputStream out = new FileOutputStream(file);
            try {
                ExcelUtils.exportExcel(excelData, out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        try {
            ExcelUtils.exportExcel(response, excelData.getName(), excelData);
        } catch (RuntimeException r) {
            r.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @BsCLog("修改当前考核信息")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/recordEdit/{id}")
    public String recordEdit(@PathVariable("id") Long id, Model model) {
        YwAppraisalRecordDO recordDO = appraisalUserService.get(id);
        YwAppraisalDataDO dataDO = null;
        List<SysFileDO> fileDOS = null;
        if (recordDO.getFileId() != null) {
            dataDO = applyService.selectOneData(recordDO.getFileId());
            fileDOS = AppraisalApplyController.getSysFileDOS(dataDO, fileService);
        }
        model.addAttribute("recordDO", recordDO);
        model.addAttribute("dataDO", dataDO);
        model.addAttribute("fileDOS", fileDOS);
        return prefix + "recordEdit";
    }

    @BsCLog("修改当前考核信息")
    @RequiresPermissions("yw:kh:kh")
    @PostMapping(value = "/recordEdit")
    @ResponseBody
    public ReturnDTO recordEdit(@RequestParam("id") Long id, @RequestParam("recordAmount") Integer recordAmount) {
        YwAppraisalRecordDO recordDO = appraisalUserService.get(id);
        if (null != recordDO) {
            recordDO.setRecordAmount(recordAmount);
            if (recordAmount == null) {
                recordAmount = 1;
            }
            recordDO.setRecordMoney(recordAmount * recordDO.getItemMoney());
            recordDO.setUpdateId(getUserId());
            return ReturnDTO.check(appraisalUserService.updateRecord(recordDO));
        }
        return ReturnDTO.error("修改失败");
    }

    @BsCLog("查看当前考核详情")
    @RequiresPermissions("yw:kh:kh")
    @GetMapping(value = "/recordDetail/{id}")
    public String recordDetail(@PathVariable("id") Long id, Model model) {
        YwAppraisalRecordDO recordDO = appraisalUserService.get(id);
        YwAppraisalDataDO dataDO = null;
        List<SysFileDO> fileDOS = null;
        if (recordDO.getFileId() != null) {
            dataDO = applyService.selectOneData(recordDO.getFileId());
            fileDOS = AppraisalApplyController.getSysFileDOS(dataDO, fileService);
        }
        model.addAttribute("recordDO", recordDO);
        model.addAttribute("dataDO", dataDO);
        model.addAttribute("fileDOS", fileDOS);
        return prefix + "recordDetail";
    }

    @BsCLog("删除考核记录")
    @RequiresPermissions("yw:kh:remove")
    @GetMapping(value = "/delete/{id}")
    @ResponseBody
    public ReturnDTO remove(@PathVariable("id") Long id) {
        return ReturnDTO.check(appraisalUserService.delete(id));
    }
}
